# Create your views here.
from django.shortcuts import render_to_response, Http404
from django.template import RequestContext
from django.core.mail import EmailMessage, BadHeaderError
from django import forms
from django.contrib.auth.models import User
from options import Options

from apps.course.models import Course
from apps.participants.models import CourseParticipant

import logging

logger = logging.getLogger('pet.apps.contact.views')

class ContactForm(forms.Form):
    subject = forms.CharField(max_length=100,widget=forms.TextInput(attrs={'size':51,}))
    message = forms.CharField(widget=forms.Textarea())
    sender = forms.EmailField(widget=forms.TextInput(attrs={'size':51,}))

@Options.option_enabled
def contact(request, username, course=None):
    TheUser = User.find_or_404(username)
    TheCourse = None
    if course: TheCourse = Course.find_or_404(course)

    if request.user.is_authenticated() and request.user.email: form = ContactForm(initial={'sender':request.user.email})
    else: form = ContactForm()
    TO_NAME = '%s %s' % (TheUser.first_name, TheUser.last_name)

    popup = True
    if 'option' in request.GET:
        popup = (request.GET.get('option','') != 'nopopup')

    if (request.method == 'POST'):
        form = ContactForm(request.POST)
        if form.is_valid():
            try:
                send_email([TheUser.email], form.cleaned_data['subject'], form.cleaned_data['message'], form.cleaned_data['sender'], course=TheCourse)
            except BadHeaderError:
                return HttpResponse('Invalid header found.')
            if not popup:
                return render_to_response('contact/done.html',{'to':TO_NAME,'sender':form.cleaned_data['sender'],},context_instance=RequestContext(request))
            else:
                return render_to_response('contact/popup-done.html',{'to':TO_NAME,'sender':form.cleaned_data['sender'],},context_instance=RequestContext(request))
    if not popup:
        return render_to_response('contact/contact.html',{'to':TO_NAME,'form':form,},context_instance=RequestContext(request))
    else:
        return render_to_response('contact/popup-contact.html',{'to':TO_NAME,'form':form,},context_instance=RequestContext(request))
    
@Options.option_enabled
def contact_course(request, course, initial_subject="", initial_message=""):
    TheCourse = Course.find_or_404(course)
    CourseParticipants = CourseParticipant.find(course)
    TO_LIST = [user.user.email for user in CourseParticipants]
    TO_NAME = course
    return(contact_list(request,course,TO_LIST,TO_NAME,initial_subject,initial_message))

@Options.option_enabled
def contact_list(request, course, TO_LIST, TO_NAME, initial_subject="", initial_message=""):
    if not isinstance(course,Course): TheCourse = Course.find_or_404(course)
    else: TheCourse = course
    initial_dict = {'subject':initial_subject,'message':initial_message}
    if request.user.is_authenticated() and request.user.email: initial_dict['sender'] = request.user.email
    form = ContactForm(initial=initial_dict)

    popup = True
    if 'option' in request.GET:
        popup = (request.GET.get('option','') != 'nopopup')

    if (request.method == 'POST'):
        form = ContactForm(request.POST)
        if form.is_valid():
            try:
                send_email(TO_LIST, form.cleaned_data['subject'], form.cleaned_data['message'], form.cleaned_data['sender'], course=TheCourse)
            except BadHeaderError:
                return HttpResponse('Invalid header found.')
            if not popup:
                return render_to_response('contact/done.html',{'to':TO_NAME,'sender':form.cleaned_data['sender'],},context_instance=RequestContext(request))
            else:
                return render_to_response('contact/popup-done.html',{'to':TO_NAME,'sender':form.cleaned_data['sender'],},context_instance=RequestContext(request))
    if not popup:
        return render_to_response('contact/contact.html',{'to':TO_NAME,'form':form,},context_instance=RequestContext(request))
    else:
        return render_to_response('contact/popup-contact.html',{'to':TO_NAME,'form':form,},context_instance=RequestContext(request))

def send_email(to_list, subject, message, sender=None, include_sender=True, course=None):
    logger.fxn_entry("to_list %s, subject %s, message <hidden for security>, sender %s, include_sender %s, course %s", to_list, subject, sender, include_sender, course)
    #Create the TO_LIST
    TO_LIST = []
    try:
        for item in to_list:
            if isinstance(item,User):
                TO_LIST.append(item.email)
            elif isinstance(item, str) or isinstance(item,unicode):
                TO_LIST.append(item)
            else:
                raise TypeError("send_email argument to_list must be User instance, string, or iterable of User instances or strings")
    except TypeError:
        if isinstance(to_list,User):
            TO_LIST = [to_list.email]
        elif isinstance(to_list,str) or isinstance(to_list,unicode):
            TO_LIST = [to_list]
        else:
            raise TypeError("send_email argument to_list must be User instance, string, or iterable of User instances or strings")
    if include_sender and sender: TO_LIST.append(sender)

    #Create the SUBJECT
    SUBJECT = ''
    if course: SUBJECT = '[' + course.course_id + ' Website] '
    SUBJECT += subject

    #Get the ReturnEmail
    ReturnEmail = Options.get_option("Noreply Address")
    if not ReturnEmail:
        logger.error("Noreply Address not configured in options. \n\t Please configure the Noreply Address before sending email.")
        raise Http404
    email = EmailMessage(SUBJECT, message, ReturnEmail, bcc=TO_LIST, headers={'Reply-To':sender} if sender else None)
    email.send(fail_silently=True)
